In this blog, I’m trying to explain the concept of hash table in c#.
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
Creating hash table
Hashtable ht =new Hashtable();
This code will create hash table with named ht.
Adding items to hash table
ht.Add(“001”,”Sachin”);
ht.Add(“002”,”Rahul”);
This code will add items to hash table, it uses add() method and has key and value parameters.
Retrieving an item value in hash table
string name=ht[001].ToString();
This code will retrieve the item value.
Removing item from hash table
ht.Remove(“001”);
This code will remove the item from the hash table with key value 001.
Example
using System;
using System.Collections;
namespace HashTableConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
Console.Write("Enter Maximum Number Of Record To Be In Hashtable = ");
int max = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= max; i++)
{
Console.Write("Enter Data =");
string data = Console.ReadLine();
ht.Add(i, data);
}
ICollection key = ht.Keys;
Console.WriteLine("\n\nData in Hashtable");
foreach (int k in key)
{
Console.WriteLine(k + ":" + ht[k]);
}
}
}
}
Leave Comment